package edu.gzhu.guli.front.service.impl;

import edu.gzhu.guli.core.common.ApplicationResult;
import edu.gzhu.guli.core.entity.Course;
import edu.gzhu.guli.core.entity.CourseOrder;
import edu.gzhu.guli.core.entity.Member;
import edu.gzhu.guli.core.entity.MemberJoinCourse;
import edu.gzhu.guli.core.repository.CourseOrderRepository;
import edu.gzhu.guli.core.repository.CourseRepository;
import edu.gzhu.guli.core.repository.MemberJoinCourseRepository;
import edu.gzhu.guli.core.repository.MemberRepository;
import edu.gzhu.guli.front.service.OrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private MemberRepository memberRepository;

    @Resource
    private MemberJoinCourseRepository memberJoinCourseRepository;

    @Resource
    private CourseOrderRepository courseOrderRepository;

    @Resource
    private CourseRepository courseRepository;

    public ApplicationResult<String> buyCourse(String username, String courseId){
        try{
            Optional<Member> checkMember = memberRepository.findByUsername(username);
            Optional<Course> checkCourse = courseRepository.findById(Long.parseLong(courseId));
            if (checkMember.isPresent()&&checkCourse.isPresent()){
                Member member = checkMember.get();
                Course course = checkCourse.get();

                MemberJoinCourse memberJoinCourse = new MemberJoinCourse();
                memberJoinCourse.setMember(member);
                memberJoinCourse.setCourse(course);
                memberJoinCourseRepository.save(memberJoinCourse);

                CourseOrder courseOrder = new CourseOrder();
                courseOrder.setMember(member);
                courseOrder.setCourse(course);
                courseOrder.setNumber("111");
                courseOrderRepository.save(courseOrder);

                course.setBuyCount(course.getBuyCount()+1);
                courseRepository.save(course);

                return ApplicationResult.succese("购买成功");
            }
            else{
                return ApplicationResult.failure("购买失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return ApplicationResult.failure("购买失败");
        }
    }
}
